package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.mapper.ZjWorkFieldMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjWorkFieldContentService;
import com.zb.service.ZjWorkFieldService;
import com.zb.service.ZjWorkModuleFieldService;
import com.zb.service.ZjWorkModuleService;
import com.zb.vo.WorkFieldContentVo;
import com.zb.vo.WorkFieldListVo;
import com.zb.vo.WorkFieldVo;
import com.zb.vo.WorkSysInitExportFieldVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单字段表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-09-26
 */
@Service
public class ZjWorkFieldServiceImpl extends ServiceImpl<ZjWorkFieldMapper, ZjWorkField> implements ZjWorkFieldService {
    @Resource
    private ZjWorkFieldMapper workFieldMapper;
    @Resource
    private ZjWorkFieldContentService workFieldContentService;
    @Resource
    private ZjWorkModuleFieldService moduleFieldService;
    @Resource
    private ZjWorkModuleService workModuleService;

    // 新增或修改工单自定义字段
    @Override
    @Transactional
    public void save(Long custAccId, WorkFieldVo fieldVo) {
        Assert.isTrue(null == workFieldMapper.existByName(custAccId, fieldVo.getId(), fieldVo.getName()), "字段名称已重复");
        ZjWorkField field = new ZjWorkField();
        BeanUtils.copyProperties(fieldVo, field);
        field.setDisabled(fieldVo.getStatus());
        if (null != field.getId()) {
            this.updateById(field);
        } else {
            field.setId(IdWorker.getId());
            field.setCustAccId(custAccId);
            this.save(field);
        }
        workFieldContentService.save(custAccId, field.getId(), fieldVo.getContentVos(), fieldVo.getDelContentIds());
    }

    // 获取工单自定义字段列表
    @Override
    public Map<String, Object> getList(Long custAccId, SelectVo selectVo) {
        QueryWrapper<ZjWorkField> wrapper = new QueryWrapper<>();
        wrapper.eq("cust_acc_id", custAccId);
        wrapper.orderByDesc("gmt_update");
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        PageUtil.setPageLimit(selectVo);
        Page<ZjWorkField> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        List<Long> workFieldIds = page.getRecords().stream().map(ZjWorkField::getId).toList();
        List<ZjWorkFieldContent> fieldContents = workFieldContentService.getByWorkFieldIds(workFieldIds);
        List<WorkFieldListVo> voList = page.getRecords().stream().map(field -> {
            WorkFieldListVo vo = new WorkFieldListVo();
            BeanUtils.copyProperties(field, vo);
            vo.setStatus(field.getDisabled());
            vo.setCreateTime(field.getGmtCreate());
            vo.setUpdateTime(field.getGmtUpdate());
            vo.setContent(fieldContents.stream().filter(con -> Objects.equals(con.getWorkFieldId(), vo.getId())).map(ZjWorkFieldContent::getVal).toList());
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据ID获取工单自定义字段详情
    @Override
    public WorkFieldVo getDetail(Long id) {
        ZjWorkField field = this.getById(id);
        Assert.isTrue(null != field, "工单自定义字段ID参数[" + id+ "]的数据不存在");
        WorkFieldVo vo = new WorkFieldVo();
        BeanUtils.copyProperties(field, vo);
        vo.setStatus(field.getDisabled());
        vo.setContentVos(workFieldContentService.getByWorkFieldId(id).stream().map(con -> {
            WorkFieldContentVo contentVo = new WorkFieldContentVo();
            contentVo.setId(con.getId());
            contentVo.setVal(con.getVal());
            return contentVo;
        }).toList());
        return vo;
    }

    // 批量启用或禁用工单自定义字段
    @Override
    public void updateDisabledBatchById(List<Long> idList, boolean status) {
        workFieldMapper.updateDisabledBatchById(idList, status);
    }

    // 批量删除工单自定义字段
    @Override
    @Transactional
    public void deleteBatchById(List<Long> ids) {
        List<ZjWorkModuleField> moduleFields = moduleFieldService.getByWorkFields(ids);
        if (!moduleFields.isEmpty()) {
            List<Long> moduleIds = moduleFields.stream().map(ZjWorkModuleField::getModuleId).distinct().toList();
            QueryWrapper<ZjWorkModule> moduleQueryWrapper = new QueryWrapper<>();
            moduleQueryWrapper.select("name");
            moduleQueryWrapper.in("id", moduleIds);
            List<Long> workFields = moduleFields.stream().map(ZjWorkModuleField::getWorkFieldId).distinct().toList();
            QueryWrapper<ZjWorkField> wrapper = new QueryWrapper<>();
            wrapper.select("name");
            wrapper.in("id", workFields);
            Assert.isTrue(false, "自定义字段["+ this.list(wrapper).stream().map(ZjWorkField::getName).collect(Collectors.joining("、"))
                    +"]已与工单模块[" + workModuleService.list(moduleQueryWrapper).stream().map(ZjWorkModule::getName).collect(Collectors.joining("、")) + "]关联，不可删除");
        }
        workFieldContentService.deleteBatchByWorkFieldIds(ids);
        this.removeByIds(ids);
    }

    // 工单字段下拉列表查询
    @Override
    public Map<String, Object> workFieldPageSelect(Long custAccId, SelectVo selectVo) {
        PageUtil.setSelectPageLimit(selectVo);
        QueryWrapper<ZjWorkField> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "type", "is_required AS required");
        wrapper.eq("cust_acc_id", custAccId).eq("is_disabled", false);
        wrapper.orderByDesc("gmt_update");
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        Page<ZjWorkField> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        List<SelectFieldVo> voList = page.getRecords().stream().map(field -> {
            return new SelectFieldVo(field.getId(), field.getName(), field.getType(), field.getRequired());
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据工单字段ID查询字段信息
    @Override
    public List<ZjWorkField> getByIds(List<Long> ids) {
        if (null == ids || ids.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkField> wrapper = new QueryWrapper<>();
        wrapper.in("id", ids);
        return this.list(wrapper);
    }

    // 获取工单自定义字段
    @Override
    public List<WorkSysInitExportFieldVo> getOrderCustomField(Long custAccId) {
        QueryWrapper<ZjWorkField> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name")
                .eq("cust_acc_id", custAccId).eq("is_disabled", false)
                .in("type", 1, 2, 3, 4, 8);
        return this.list(wrapper).stream().map(field -> {
            return new WorkSysInitExportFieldVo(field.getId(), field.getName());
        }).toList();
    }
}
